package com.tdt.alarm.model;

import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tdt.alarm.R;
import com.tdt.alarm.controller.OneShotAlarm;
import com.tdt.alarm.controller.fragment.Home;

public class MyArrayAdapter extends ArrayAdapter<SetAlarm> {
	String[] repeat = { "Sun" ,"Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	Activity context;
	int layoutId;
	List<SetAlarm> arrAlarm;
	Toast mToast;
	AlarmDBHelper alarmDB;
	ListView listView;
	View lastView = null;

	public MyArrayAdapter(Activity context, int layoutId,
			List<SetAlarm> arrAlarm2, ListView listView) {
		super(context, layoutId, arrAlarm2);
		this.context = context;
		this.layoutId = layoutId;
		this.arrAlarm = arrAlarm2;
		alarmDB = new AlarmDBHelper(context);
		this.listView = listView;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = context.getLayoutInflater();
		convertView = inflater.inflate(layoutId, null);
		if (arrAlarm.size() > 0) {
			final TextView timeDisplay = (TextView) convertView
					.findViewById(R.id.tvTime);
			final TextView labelDisplay = (TextView) convertView
					.findViewById(R.id.tvLabel);
			final TextView repeatDisplay = (TextView) convertView
					.findViewById(R.id.tvRepeat);
			final CheckBox checkActive = (CheckBox) convertView
					.findViewById(R.id.chkActive);

			final SetAlarm alarm = arrAlarm.get(position);
			timeDisplay.setText(alarm.getTime().toString());
			if (alarm.getTime().getMinute() < 10) {
				timeDisplay.setText(alarm.getTime().getHour() + ":0"
						+ alarm.getTime().getMinute());
			}
			if (alarm.getTime().getHour() < 10) {
				timeDisplay.setText("0" + alarm.getTime().getHour() + ":"
						+ alarm.getTime().getMinute());
			}
			if (alarm.getTime().getHour() < 10
					&& alarm.getTime().getMinute() < 10) {
				timeDisplay.setText("0" + alarm.getTime().getHour() + ":0"
						+ alarm.getTime().getMinute());
			}
			labelDisplay.setText(alarm.getLabel().toString());
			boolean[] repeatingDays = alarm.getRepeatingDays();
			int countRepeat = 0;
			repeatDisplay.setText("");
			for (int i = 0; i < 7; i++) {
				if (repeatingDays[i] == true) {
					repeatDisplay.setText(repeatDisplay.getText() + " "
							+ repeat[i]);
					countRepeat++;
				}
			}
			if (countRepeat == 0) {
				repeatDisplay.setText("Never repeat");
			}
			if (countRepeat == 7) {
				repeatDisplay.setText("All day");
			}

			if (alarm.isCheckActive())
				checkActive.setChecked(true);
			else
				checkActive.setChecked(false);

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					checkActive.setChecked(!checkActive.isChecked());

					// Utils.editAlarmList(arrAlarm, position,
					// checkActive.isChecked());
					// update
					SetAlarm setAlarm = arrAlarm.get(position);

					setAlarm.setCheckActive(checkActive.isChecked());
					// Toast.makeText(context,
					// position+" check="+setAlarm.isCheckActive(),
					// Toast.LENGTH_SHORT).show();
					alarmDB.updateAlarm(setAlarm);
					// fm.setOneShowAlarm(null, position, arrAlarm);

					Calendar alarmPoint = null;
					Intent intent = new Intent(context, OneShotAlarm.class);
					PendingIntent sender = PendingIntent.getBroadcast(
							getContext(), 0, intent, 0);
					SetAlarm alarm = Utils.getCurrentAlarm(position, arrAlarm);
					Toast.makeText(
							context,
							" gio vua lay " + alarm.getTime().getHour() + ":"
									+ alarm.getTime().getMinute(),
							Toast.LENGTH_SHORT).show();
					alarmPoint = Calendar.getInstance();
					alarmPoint.set(2015, 10, 27, alarm.getTime().getHour(),
							alarm.getTime().getMinute());

					Calendar calendar = Calendar.getInstance();

					int distance = alarmPoint.get(Calendar.HOUR) * 3600
							+ alarmPoint.get(Calendar.MINUTE) * 60
							- calendar.get(Calendar.HOUR) * 3600
							- calendar.get(Calendar.MINUTE) * 60
							- calendar.get(Calendar.SECOND);
					if (distance < 0)
						distance += 86400;
					calendar.add(Calendar.SECOND, distance);

					// Schedule the alarm!
					AlarmManager am = (AlarmManager) context
							.getApplicationContext().getSystemService(
									Context.ALARM_SERVICE);

					// Tell the user about what we did.

					if (mToast != null) {
						mToast.cancel();
					}
					int hour = 0, min = 0, sec = 0;
					int time = distance;
					while (time > 60) {
						if (time >= 3600) {
							hour = time / 3600;
							time = time % 3600;
						} else if (time >= 60) {
							min = time / 60;
							time = time % 60;
							sec = time;
						}
					}

					// mToast = Toast.makeText(context, "Next alarm in: "
					// + hour + "h " + min + "m " + sec + "s",
					// Toast.LENGTH_SHORT);
					// mToast.show();
					if (checkActive.isChecked()) {
						am.set(AlarmManager.RTC_WAKEUP,
								calendar.getTimeInMillis(), sender);
					} else {
						am.cancel(sender);
						// Toast.makeText(getContext().getApplicationContext(),
						// "Uncheck position = " + position,
						// Toast.LENGTH_SHORT).show();
					}
					// Fragment1.findNearlyAlarm(Utils.getAlarmActiveFirst(arrAlarm),
					// arrAlarm);
				}
			});

			// convertView.setOnLongClickListener(new OnLongClickListener() {
			// @Override
			// public boolean onLongClick(View v) {
			// AlertDialog.Builder builder = new AlertDialog.Builder(
			// context);
			// builder.setTitle("Alarm Actions");
			// // builder.setView(View.inflate(context,
			// // R.layout.alarm_actions, null));
			// builder.setItems(R.array.alarm_actions,
			// new DialogInterface.OnClickListener() {
			// @Override
			// public void onClick(DialogInterface arg0,
			// int which) {
			// switch (which) {
			// case 0:
			// Intent iEdit = new Intent(context,
			// AlarmModify.class);
			// iEdit.putExtra("pos", position);
			// context.startActivity(iEdit);
			// break;
			// case 1: // xóa
			// SetAlarm alarmToDelete = arrAlarm
			// .get(position);
			// arrAlarm.remove(position);
			// // Collections.reverse(arrAlarm);
			// // Utils.updateFile(arrAlarm);
			// // Delete in DB
			// alarmDB.deleteAlarm(alarmToDelete
			// .getId());
			// Intent i = new Intent(context,
			// MainActivity.class);
			// notifyDataSetChanged();
			//
			// break;
			// default:
			// Toast.makeText(context,
			// "duplicate " + position,
			// Toast.LENGTH_LONG).show();
			// break;
			// }
			// }
			// });
			//
			// builder.show();
			// return false;
			// }
			//
			// });

			// edit alarm
			convertView.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					if (lastView != null) {
						lastView.setBackgroundColor(Color.TRANSPARENT);
					}
					lastView = v;
					SetAlarm setAlarmToEdit = arrAlarm.get(position);
					Home.editAlarm(setAlarmToEdit);
					Toast.makeText(context, "Edit mode ! ", Toast.LENGTH_LONG)
							.show();
					v.setBackgroundColor(Color.GREEN);
					listView.setFocusableInTouchMode(false);
					return true;
				}
			});
			// delete one row
			SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
					listView,
					new SwipeDismissListViewTouchListener.DismissCallbacks() {
						@Override
						public boolean canDismiss(int position) {
							return true;
						}

						@Override
						public void onDismiss(ListView listView,
								int[] reverseSortedPositions) {
							for (int position : reverseSortedPositions) {
								SetAlarm alarmToDelete = arrAlarm.get(position);
								arrAlarm.remove(position);
								// Delete in DB
								alarmDB.deleteAlarm(alarmToDelete.getId());
								// notifyDataSetChanged();
							}
							notifyDataSetChanged();
						}
					});
			convertView.setOnTouchListener(touchListener);

		}
		return convertView;
	}
}
